<p-confirmDialog [baseZIndex]="10000" rejectButtonStyleClass="p-button-text"></p-confirmDialog>
<app-breadcrumbs [items]="breadcrumbs">
    <div page-help>
        <p>
            Administrative users can modify user privileges and passwords by clicking on the user name below. More
            information in documentation in
            <a href="https://stork.readthedocs.io/en/latest/usage.html#managing-users" target="blank"
                >user and password management</a
            >
            chapter.
        </p>
        <dl>
            <dt>ID</dt>
            <dd>a sequential identifier number used internally by Stork.</dd>
            <dt>Login</dt>
            <dd>a friendly name identifying the user. It is unique for a given authentication method.</dd>
            <dt>Email</dt>
            <dd>an optional property.</dd>
            <dt>Group</dt>
            <dd>a label of a group that the user belongs to.</dd>
            <dt>Authentication</dt>
            <dd>
                an identifier of the method used to authenticate a user. The internal authentication is a default method
                using login and password stored in the Stork database.
            </dd>
            <dt>External ID</dt>
            <dd>
                an identifier returned by an external authentication service. It is not specified if the internal
                authentication method is used.
            </dd>
        </dl>
    </div>
</app-breadcrumbs>

<p-tabMenu [model]="tabs" [activeItem]="activeItem" styleClass="mb-2" [scrollable]="true">
    <ng-template pTemplate="item" let-item let-i="index">
        <a role="menuitem" pRipple [routerLink]="item.routerLink" class="p-ripple p-element p-menuitem-link">
            <div style="display: flex; justify-content: space-between">
                <div class="p-menuitem-icon" [ngClass]="item.icon" *ngIf="item.icon"></div>
                <div class="p-menuitem-text">
                    <b>{{ item.label }}</b>
                </div>
                <div class="pi pi-times close-tab-btn" (click)="closeTab($event, i)" *ngIf="i !== 0"></div>
            </div>
        </a>
    </ng-template>
</p-tabMenu>

<div *ngIf="activeTabIdx === 0">
    <div style="display: flex; justify-content: space-between; margin: 10px">
        <div style="display: flex">
            <button
                type="button"
                pButton
                label="Create User Account"
                id="create-user-account-button"
                icon="pi pi-plus"
                style="margin-right: 20px"
                (click)="showNewUserTab()"
            ></button>
        </div>
    </div>

    <p-menu #userMenu [popup]="true" [model]="userMenuItems"></p-menu>
    <p-table
        #usersTable
        [value]="users"
        [paginator]="true"
        [rows]="10"
        [lazy]="true"
        (onLazyLoad)="loadUsers($event)"
        [totalRecords]="totalUsers"
        [rowsPerPageOptions]="[10, 30, 100]"
        [showCurrentPageReport]="true"
        currentPageReportTemplate="{currentPage} of {totalPages} pages"
        stateStorage="session"
        stateKey="users-table-session"
        styleClass="p-datatable-striped"
    >
        <ng-template pTemplate="header">
            <tr>
                <th>Login</th>
                <th>Email</th>
                <th>First name</th>
                <th>Last name</th>
                <th>Group</th>
                <th>Authentication</th>
                <th>External ID</th>
            </tr>
        </ng-template>
        <ng-template pTemplate="body" let-u>
            <tr>
                <td align="center">
                    <a routerLink="/users/{{ u.id }}">{{ u.login | placeholder }}</a>
                    <sup *ngIf="auth.currentUserValue.id === u.id"
                        ><p-tag styleClass="ml-1" severity="success" value="It's you"
                    /></sup>
                </td>
                <td align="center">
                    <a routerLink="/users/{{ u.id }}">{{ u.email | placeholder }}</a>
                </td>
                <td align="center">{{ u.name | placeholder }}</td>
                <td align="center">{{ u.lastname | placeholder }}</td>
                <td align="center">{{ getGroupName(u.groups[0]) }}</td>
                <td align="center">{{ u.authenticationMethodId }}</td>
                <td align="center">{{ u.externalId | placeholder }}</td>
            </tr>
        </ng-template>
        <ng-template pTemplate="emptymessage">
            <tr>
                <td colspan="7">No users found.</td>
            </tr>
        </ng-template>
        <ng-template pTemplate="paginatorright" let-state>
            Total: {{ state.totalRecords > 0 ? state.totalRecords : '0' }}
            {{ state.totalRecords === 1 ? 'user' : 'users' }}
        </ng-template>
    </p-table>
</div>

<div *ngIf="existingUserTab" class="p-component">
    <div style="display: flex; margin: 10px">
        <div class="grid mt-2 max-w-50rem word-break-all">
            <div class="col-12 sm:col-3">
                <b>ID:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ userTab.user.id }}
            </div>
            <div class="col-12 sm:col-3">
                <b>Login:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ userTab.user.login }}
            </div>
            <div class="col-12 sm:col-3">
                <b>Email:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ userTab.user.email | placeholder }}
            </div>
            <div class="col-12 sm:col-3">
                <b>Last name:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ userTab.user.lastname | placeholder }}
            </div>
            <div class="col-12 sm:col-3">
                <b>First name:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ userTab.user.name | placeholder }}
            </div>
            <div class="col-12 sm:col-3">
                <b>Group:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ getGroupName(userTab.user.groups[0]) }}
            </div>
            <div class="col-12 sm:col-3">
                <b>Authentication:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ userTab.user.authenticationMethodId }}
            </div>
            <div class="col-12 sm:col-3">
                <b>External ID:</b>
            </div>
            <div class="col-12 sm:col-9">
                {{ userTab.user.externalId | placeholder }}
            </div>
            <div class="col-12 flex gap-3">
                <button
                    type="button"
                    pButton
                    label="Edit"
                    id="edit-user-button"
                    icon="pi pi-pencil"
                    (click)="editUserInfo(userTab)"
                    class="flex-none"
                ></button>
                <button
                    type="submit"
                    pButton
                    class="p-button-danger flex-none"
                    label="Delete"
                    id="delete-user-button"
                    icon="pi pi-trash"
                    (click)="confirmDeleteUser()"
                ></button>
            </div>
        </div>
    </div>
</div>

<div *ngIf="newUserTab || editedUserTab" class="p-component">
    <div class="m-2 max-w-100rem">
        <div class="grid">
            <div class="col-12 lg:col-4">
                <p-panel header="Creating new account" *ngIf="newUserTab">
                    <p>
                        To create a new user account, please specify user login, first name, and last name. An email
                        address is optional but strongly recommended. If an email is provided, the user can sign in
                        either using the login or the email address. The password is mandatory and must be at least 8
                        characters long.
                    </p>
                    <br />
                    <p>
                        The user must be associated with an existing system group. Currently there are two groups
                        available: super-admin and admin. Users belonging to the super-admin group have full control
                        over the system, including creating and modifying user accounts. Users belonging to the admin
                        group have similar permissions, with the exception that they are not allowed to create and/or
                        modify user accounts. However, they are allowed to update their own passwords.
                    </p>
                </p-panel>
                <p-panel header="Editing an account" *ngIf="editedUserTab">
                    <p>
                        Use this form to modify user account information, add a missing email address, or change the
                        group that the user is associated with.
                    </p>
                    <br />
                    <p>The user password remains unchanged if it is left blank while saving the form.</p>
                    <p-message
                        *ngIf="!isInternalUser"
                        severity="info"
                        text="The external authorization service '{{
                            userTab.user.authenticationMethodId
                        }}' manages this user
                            profile. It can be only modified via the administrator panel of the authentication service."
                    >
                    </p-message>
                </p-panel>
            </div>
            <div class="col-12 lg:col-8">
                <form [formGroup]="userForm">
                    <p-panel header="User account">
                        <div class="field grid" *ngIf="isInternalUser">
                            <label for="userLogin" class="col-12 sm:col-3">Login*:</label>
                            <div class="col-12 sm:col-9">
                                <input
                                    pInputText
                                    type="text"
                                    formControlName="userLogin"
                                    id="userLogin"
                                    class="user-input"
                                    pattern="[a-zA-Z0-9_]+"
                                    title="Login must only contain letters, digits, or underscore."
                                />
                            </div>
                            <div class="col-12 sm:col-9 sm:col-offset-3 mt-2" *ngIf="isFeedbackNeeded('userLogin')">
                                <p-message
                                    severity="error"
                                    [text]="
                                        buildFeedbackMessage(
                                            'userLogin',
                                            'Login must only contain letters, digits, or underscore'
                                        )
                                    "
                                ></p-message>
                            </div>
                        </div>
                        <div class="field grid" *ngIf="isInternalUser">
                            <label for="userEmail" class="col-12 sm:col-3">Email:</label>
                            <div class="col-12 sm:col-9">
                                <input
                                    pInputText
                                    type="text"
                                    class="user-input"
                                    formControlName="userEmail"
                                    id="userEmail"
                                    title="User email address."
                                />
                            </div>
                            <div class="col-12 sm:col-9 sm:col-offset-3 mt-2" *ngIf="isFeedbackNeeded('userEmail')">
                                <p-message severity="error" [text]="buildFeedbackMessage('userEmail')"></p-message>
                            </div>
                        </div>
                        <div class="field grid" *ngIf="isInternalUser">
                            <label for="userFirst" class="col-12 sm:col-3">First name*:</label>
                            <div class="col-12 sm:col-9">
                                <input
                                    pInputText
                                    type="text"
                                    formControlName="userFirst"
                                    id="userFirst"
                                    class="user-input"
                                    pattern="^[\w](?!.*\s{2,}).*[\w]$"
                                    title="Must contain at least 2 word characters. Can't begin nor end with whitespace. Only single whitespaces are allowed."
                                />
                            </div>
                            <div class="col-12 sm:col-9 sm:col-offset-3 mt-2" *ngIf="isFeedbackNeeded('userFirst')">
                                <p-message
                                    severity="error"
                                    [text]="
                                        buildFeedbackMessage(
                                            'userFirst',
                                            'Must contain at least 2 word characters. Can\'t begin nor end with whitespace. Only single whitespaces are allowed.'
                                        )
                                    "
                                ></p-message>
                            </div>
                        </div>
                        <div class="field grid" *ngIf="isInternalUser">
                            <label for="userLast" class="col-12 sm:col-3">Last name*:</label>
                            <div class="col-12 sm:col-9">
                                <input
                                    pInputText
                                    type="text"
                                    formControlName="userLast"
                                    id="userLast"
                                    class="user-input"
                                    pattern="^[\w](?!.*\s{2,}).*[\w]$"
                                    title="Must contain at least 2 word characters. Can't begin nor end with whitespace. Only single whitespaces are allowed."
                                />
                            </div>
                            <div class="col-12 sm:col-9 sm:col-offset-3 mt-2" *ngIf="isFeedbackNeeded('userLast')">
                                <p-message
                                    severity="error"
                                    [text]="
                                        buildFeedbackMessage(
                                            'userLast',
                                            'Must contain at least 2 word characters. Can\'t begin nor end with whitespace. Only single whitespaces are allowed.'
                                        )
                                    "
                                ></p-message>
                            </div>
                        </div>
                        <div class="field grid">
                            <label for="userGroup" class="col-12 sm:col-3">Group*:</label>
                            <div class="col-12 sm:col-9">
                                <p-dropdown
                                    [options]="userGroups"
                                    formControlName="userGroup"
                                    id="userGroup"
                                    [style]="{ width: '14em' }"
                                    title="Group where the user will belong to."
                                ></p-dropdown>
                            </div>
                            <div class="col-12 sm:col-9 sm:col-offset-3 mt-2" *ngIf="isFeedbackNeeded('userGroup')">
                                <p-message severity="error" [text]="buildFeedbackMessage('userGroup')"></p-message>
                            </div>
                        </div>
                        <div class="field grid" *ngIf="isInternalUser">
                            <label for="userPassword" class="col-12 sm:col-3">Password*:</label>
                            <div class="col-12 sm:col-9">
                                <p-password
                                    formControlName="userPassword"
                                    inputId="userPassword"
                                    inputStyleClass="user-input"
                                    styleClass="password-component"
                                    [pattern]="passwordPattern"
                                    title="Must only contain letters, digits, or special characters and must be at least 8 characters long."
                                    [toggleMask]="true"
                                ></p-password>
                            </div>
                            <div class="col-12 sm:col-9 sm:col-offset-3 mt-2" *ngIf="isFeedbackNeeded('userPassword')">
                                <p-message
                                    severity="error"
                                    [text]="
                                        buildFeedbackMessage(
                                            'userPassword',
                                            'Password must only contain letters, digits, or special characters.'
                                        )
                                    "
                                ></p-message>
                            </div>
                        </div>
                        <div class="field grid" *ngIf="isInternalUser">
                            <label for="userPassword2" class="col-12 sm:col-3">Repeat password*:</label>
                            <div class="col-12 sm:col-9">
                                <p-password
                                    [feedback]="false"
                                    formControlName="userPassword2"
                                    inputId="userPassword2"
                                    inputStyleClass="user-input"
                                    styleClass="password-component"
                                    title="Must only contain letters, digits, or special characters and must be at least 8 characters long."
                                    [toggleMask]="true"
                                ></p-password>
                            </div>
                            <div
                                class="col-12 sm:col-9 sm:col-offset-3 mt-2"
                                *ngIf="isFeedbackNeeded('userPassword2', true)"
                            >
                                <p-message
                                    severity="error"
                                    [text]="buildFeedbackMessage('userPassword2', '', true)"
                                ></p-message>
                            </div>
                        </div>
                        <div>
                            <button
                                type="submit"
                                pButton
                                [disabled]="userForm.invalid"
                                class="p-button-success"
                                icon="pi pi-pencil"
                                label="Save"
                                id="save-button"
                                (click)="userFormSave()"
                            ></button>
                            <button
                                type="submit"
                                pButton
                                [disabled]="false"
                                class="p-button-secondary ml-2"
                                icon="pi pi-times"
                                label="Cancel"
                                id="cancel-button"
                                (click)="userFormCancel()"
                            ></button>
                        </div>
                    </p-panel>
                </form>
            </div>
        </div>
    </div>
</div>
